package zl.controller;

import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import zl.entity.User;
import zl.service.ServiceImpl.UserServiceImpl;
import zl.service.UserService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@RestController
@ResponseBody
public class UserController {

    UserService userService=new UserServiceImpl();

    @RequestMapping("/login")
    public String login(String account,String password) {
        User user=userService.selectUserByMessage(account, password);
        System.out.println(user);
        JSONObject jsonObject=new JSONObject();
        if (user!=null){
            jsonObject.put("code",0);
            jsonObject.put("msg","登陆成功！");
        }
        else{
            jsonObject.put("code",0);
            jsonObject.put("msg","登陆失败！");
        }
        return jsonObject.toString();
    }

    @RequestMapping("/register")
    public String register(String account,String password){
        JSONObject jsonObject=new JSONObject();
        if(selectUserByAccount(account)==null){
            userService.saveUser(account,password);
            jsonObject.put("code",0);
            jsonObject.put("msg","注册成功！");
        }
        else{
            jsonObject.put("code",0);
            jsonObject.put("msg","注册失败！");
        }
        return jsonObject.toString();
    }

    @RequestMapping("/account_check")
    public String accountCheck(String account, HttpServletResponse response) throws IOException {
        User user=userService.selectUserByAccount(account);
        if(user!=null){
            return "no";
        }
        else {
            return "yes";
        }
    }

    @RequestMapping("/index")
    public String mainPage() {
        return "index";
    }

    public User selectUserByAccount(String account){
        return userService.selectUserByAccount(account);
    }
}
